package com.kasax.android.arch.handler;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.NonNull;

import com.kasax.android.arch.utils.LogUtils;

/**
 * 全局异常捕获处理
 */
public class CommonCrashHandler implements Thread.UncaughtExceptionHandler {
    private CrashCallback mCallback;

    private CommonCrashHandler() {

    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        handleException(t, e);
    }


    public static interface CrashCallback {
        void handleException(Thread thread, Throwable throwable);
    }

    private static class Singleton {
        private static CommonCrashHandler INSTANCE = new CommonCrashHandler();
    }

    public static CommonCrashHandler getInstance() {
        return Singleton.INSTANCE;
    }

    public void init(Application application, CrashCallback callback) {
        this.mCallback = callback;
        new Handler(application.getMainLooper(), msg -> false)
                .post(() -> {
                    while (true) {
                        try {
                            Looper.loop();
                        } catch (Exception e) {
                            // 这里会出现异常,在这里进行捕获
                            handleException(Thread.currentThread(), e);
                        }
                    }
                });
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    private void handleException(@NonNull Thread t, @NonNull Throwable e) {
        LogUtils.e("App crash threadId: " + t.getId() + " , errorMsg: " + e.getMessage());
        if (mCallback != null) {
            mCallback.handleException(t, e);
        }
    }
}
